using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure.BaseRepository;
using System;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 删除医院命令处理程序
    /// 处理医院删除逻辑
    /// </summary>
    public class DeleteHospitalHandler : IRequestHandler<DeleteHospitalCommand, APIResult<bool>>
    {
        private readonly IRepository<Hospital> _hospitalRepository;
        private readonly ILogger<DeleteHospitalHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DeleteHospitalHandler(
            IRepository<Hospital> hospitalRepository,
            ILogger<DeleteHospitalHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除医院请求
        /// </summary>
        public async Task<APIResult<bool>> Handle(DeleteHospitalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始删除医院，ID：{Id}", request.Id);

                // 查找医院
                var hospital = await _hospitalRepository.GetAsync(h => h.Id == request.Id && !h.IsDeleted);

                if (hospital == null)
                {
                    _logger.LogWarning("未找到ID为 {Id} 的医院", request.Id);
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "未找到该医院"
                    };
                }

                // 执行软删除
                hospital.IsDeleted = true;
                hospital.UpdateTime = DateTime.Now;

                var result = await _hospitalRepository.UpdateAsync(hospital);
                if (result <= 0)
                {
                    _logger.LogError("删除医院失败，数据库操作失败");
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "删除医院失败"
                    };
                }

                _logger.LogInformation("医院删除成功，ID：{Id}", request.Id);

                return new APIResult<bool>
                {
                    Code = APIEnum.OK,
                    Message = "医院删除成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除医院时发生错误，ID：{Id}", request.Id);
                return new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "删除失败：" + ex.Message
                };
            }
        }
    }
}